/**
 * @author fanxuean
 * @link fanshine124@gmail.com
 * @description 用户基本信息页面包装器，采用惰性实例化单体模式，入口是init函数，返回包装器对象
 * @return Object {}
 */
MIDB.Model.UserInfo = (function(){
    var uniqueInstance;
    function constructor() {
        var p = {};
        // var getUserInfo = function() {
        //     $.ajax({
        //       url: MIDB.ajaxUrl.userInfo,
        //       type: 'POST',
        //       dataType: 'xml/html/script/json/jsonp',
        //       data: {param1: 'value1'},
        //       complete: function(xhr, textStatus) {
        //         //called when complete
        //       },
        //       success: function(data, textStatus, xhr) {
        //         if(!!data) compileUserInfo(data);
        //       },
        //       error: function(xhr, textStatus, errorThrown) {
        //         //called when there is an error
        //       }
        //     });
        // };
        var compileUserInfo = function(data) {
            var tmpl = p.tmpl.html(),
                doTtmpl = doT.template(tmpl);
            p.tmplContainer.html(doTtmpl(data));
            bindEvent();
        };
        var bindEvent = function() {
            p.tmplContainer.find('input[name=saveUserInfo]').click(function(event) {
                var d = p.tmplContainer.find('form[name=user_info]').serialize();
                var paramArr = {};
                $(d.split('&')).each(function() {
                    var item = this.split('=');
                    var name = item[0];
                    var value = item[1];
                    paramArr[name] = value;
                });

                updateUserInfo(JSON.stringify(paramArr));
                event.stopPropagation();
            });
        };
        var updateUserInfo = function(param) {
            $.ajax({
                url: MIDB.ajaxUrl.user_info,
                type: 'POST',
                dataType: 'json',
                data: {atype: 'u', param: param},
                complete: function(xhr, textStatus) {
                //called when complete
                },
                success: function(data, textStatus, xhr) {
                    if(data == 1) {
                        $.ligerDialog.alert('更新用户信息成功');
                    } else {
                        $.ligerDialog.alert('更新用户信息失败');
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    $.ligerDialog.alert('更新用户信息失败');
                }
            });
            
        };
        return {
            init: function(options) {
                p = $.extend({}, p||{}, options || {});
                // getUserInfo();
                compileUserInfo(MIDB.cache.user);
                return this;
            }
        };
    }
    return {
        getInstance : function() {
            if (!uniqueInstance) {
                uniqueInstance = constructor();
            }
            return uniqueInstance;
        }
    };
})();